// ==UserScript==
// @name        Salon25
// @namespace   http://juljas.net/
// @description Rozszerzenia do Salonu24, v1.0.26
// @copyright   (C) 2008-2010, greasemonkey (greasemonkey.salon24.pl) & Jan Słupski (follow.salon24.pl)
// @include     http://*.salon24.pl/*
// @exclude     http://*http://*.salon24.pl/*
//

$appname = 'Salon25';
$version = '1.0.26';

/* http://code.google.com/p/salon25/w/edit/Funkcje
#summary Funkcje skryptu Salon25
#labels Featured
= Funkcje działające =
  * górny (czarny) pasek menu
    * link 'obserwowane'
    * informacja o liczbie notek z nieprzeczytanymi komentarzami w obserwowanych (+podświetlenie)
    * kliknięcie w liczbę nieprzeczytanych notek przenosi do pierwszego nieczytanego komentarza pierwszej notki
    * zarządzanie wyglądem górnego menu (ukrywanie pozycji menu, skracanie nazw linków)
    * informacja o nowej wiadomości w skrzynce pocztowej (automatyczna aktualizacja)
    * automatyczna aktualizacja informacji o poczcie i obserwowanych
  * strona główna
    * przywrócenie użytkownikowi decyzji czy wchodzi do lubczasopisma czy do boki blogera
    * "znormalizowany" wygląd notek lubczasopismowych na SG (nick pod notką a nie w tytule)
  * edycja notki
    * edycja notki w czystym HTML - przycisk w edytorze WYSIWYG: "Żródło dokumentu"
  * edycja komentarza
    * podgląd komentarza (przed zapisaniem)
    * przycisk 'cytuj zaznaczenie' przy edycji komentarza
    * przycisk 'cytuj komentarz' przy edycji odpowiedzi na komentarz
    * naciśnięcie 'Skomentuj' notkę wstawia '@autor' do tytułu komentarza
  * blokowanie trolli
    * dostęp do opcji 'zablokuj' autora komentarza na każdym blogu
    * dostęp do opcji 'zablokuj' autora bloga (przycisk w jego profilu)
  * wewnętrzna poczta
    * 'wyślij wiadomość' do autora komentarza - ikona przy każdym komentarzu
    * 'wyślij wiadomość' w profilu każdego bloga
  * obserwowane
    * kliknięcie w liczbę nowych komentarzy na liście obserwowanych -> skok do pierwszego nieczytanego komentarza
    * sortuj obserwowane również po dacie (tylko przy domyślnym sortowaniu po liczbie komentarzy)
  * inne
    * na stronie głównej bloga (np. http://follow.salon24.pl/) tytuł notki jest permalinkiem do niej (np. http://follow.salon24.pl/240256,wiecej-zdjec-z-urodzin)
    * eksperymentalnie: informacje o nowych wersjach skryptu (+link do instalacji i changeloga)
    * informacja i możliwość przełączania filtrów
    * menu konfiguracyjne
    * mniejsza czcionka w 'aktywne dyskuje'
    * obsługa Google Chrome (poza częścią funkcji)

= Błędy w powyższych funkcjach =
  * kontrola działania skryptu dla niezalogowanych
  * podgląd komentarza nie filtruje tego co filtruje Salon (np. `<script>`, `<object>`, itp.). Warto by było choć częściowo uzupełnić
  * powolne działanie na stronie z dużą ilością komentarzy (np. http://mediaobywatelskie2.salon24.pl/141325,znosimy-wymog-akceptacji-nosg-ale)
  * nie działa: wygodniejsza obsługa 'dodaj do obserwowanych' w notce (bez okienka dialogowego, bez przeładowywania strony)
  * podgląd komentarza gdy do notki nie ma jeszcze żadnych komentarzy
  * Nie działa link "Zaloguj" gdy menu konfiguracyjne wyświetlone jest dla niezalogowanego użytkownika

= Planowane funkcje =
  * rozbudowa menu konfiguracyjnego (wedle zapotrzebowania)

= Pomysły na dalsze funkcje =
  * formatowanie cytowania (łamanie wierszy + `>` na początku linii)
  * podgląd notki (w trakcie edycji)
  * podgląd profilu (w trakcie edycji)
  * jednoetapowe wklejanie zdjęcia z dysku?!
  * hover na obserwowanych pokazuje ile i gdzie nowych odpowiedzi (tylko miejsca mało), chyba że jakieś okienko (+ linki)
  * logowanie zawsze z domeny salon24.pl (a nie domen poszczególnych blogów) bo menadżer haseł głupieje i nie wpisuje zapamiętanego hasła (iframe?)
  * logowanie permanentne - a nie reset logowania po każdym wyjściu z przeglądarki, jako opcja - checkboxem (zmiana cookie z sesyjnego na expire in a week?)
  * funkcje z Saluuuunu 1.0? (punktowanie/chowanie trolli, ...)
  * kompatybilność z Operą, Safari
  * łatwo HTML do komentarzy (w szczególności: linki, obrazki, podstawowe formatowanie)

= Funkcje już w standardzie Salonu24 =
  * edycja komentarza
    * pole odpowiedzi pod komentarzem na który odpowiadam
    * nie dopisuje '#commentadd' do adresu URL po dodaniu komentarza
  * kasowanie komentarzy
    * opcja 'skasuj' do moich komentarzy
    * opcja 'skasuj' do komentarzy na moim blogu
  * obserwowane
    * kasowanie z listy obserwowanych wielu notek na raz
  * inne
    * poprawia 'link do komentarza' (right-mouse-click -> Copy Link Location)
    * przyciski 'nowa notka', 'edytuj notkę' na własnym blogu

_(w komentarzach poniżej możesz dopisać własne propozycje)_
<wiki:comment>Funkcje END</wiki:comment>
*/
/*
TODO internal

TIPS
  * zamiana id -> nick (wyślij prywatną wiadomość)
  * zamiana nick -> id (blog, komentarz -> zablokuj...)
  * z powodu specyficznej(!) implementacji bezpieczeństwa większość stron z
    http://admin.salon24.pl/ ładuje się tylko jeśli Referer: jest pusty 
    lub ustawiony na: http://admin.salon24.pl/*
  * W związku z powyższym strony administracyjne są ładowane przy pomocy
    'admin-forward', czyli poprzez załadowanie strony pośredniej 
    http://admin.salon24.pl/posts z odpowiednio ustawionym linkiem do kotwicy
    (#j-*), co skrypt przechwytuje i dokonuje kolejnego skoku do docelowego
    urla.  Dodatkowo mechanizm "przechwytuje" naciśnięcie 'Back' w
    przeglądarce, żeby na owej podstronie pośredniej się nie zapętlać.

*/

function init_globals() {

  $=unsafeWindow.$ // jquery

  $state = {
    is_logged : false,
    my_domain : undefined,
    blog_domain : undefined,
    blog_author_id : undefined,
    blog_author_name : undefined,
    post_id : undefined,
    
    watched_new_answers : -1,
    watched_first_link : undefined,
    watched_first_title : 0,
    watched_link : undefined,
    watchedcount_link : undefined,
    watched_cache : undefined,

    newmails : 0,
    newmails_li : undefined,

    add_to_fav : undefined,
    default_menu_names : {},
    advanced_menu_magic : 0,
  };


  $consts = {
    show_last_hash : '#show-last-',
    watch_page_url : 'http://admin.salon24.pl/posts-comments-watch/',
    postedit_page_url : 'http://admin.salon24.pl/posts-edit/',
    quote_start : "<i>",
    quote_end : "</i>\n\n",
    xquote_start : "<div style='font-style: italic; border-left: solid 1px gray; padding-left: 3px'>",
    xquote_end : "</div>\n\n",
    project_url : 'http://code.google.com/p/salon25/',
    admin_url : 'http://admin.salon24.pl/',
    admin_goto_url : 'http://admin.salon24.pl/posts#j-',
    admin_goto_hash : 'j-',
    update_delay : GM_getValue("update_delay", 60),
    version_check_url : "https://salon25.googlecode.com/svn/wiki/Wersja.wiki",
  };


  $media = { 
    //xxd -i lock.png | xargs echo | sed -e 's/0x/%/g' -e 's/, //g' -e 's/%50%4e%47/PNG/g'
    lock :  "data:image/png,%89PNG%0d%0a%1a%0a%00%00%00%0d%49%48%44%52%00%00%00%10%00%00%00%10%02%03%00%00%00%62%9d%17%f2%00%00%00%01%73%52%47%42%00%ae%ce%1c%e9%00%00%00%0c%50%4c%54%45%79%79%79%a0%a0%a0%ca%ca%ca%ff%ff%ff%00%e3%1d%01%00%00%00%34%49%44%41%54%08%d7%63%f8%0f%04%0c%10%e2%49%3d%90%98%1e%0d%24%a2%a7%03%89%fc%e7%40%c2%fe%f3%7f%86%3f%0c%0c%40%62%d5%0a%20%31%73%06%0a%01%16%03%c9%c2%4d%01%00%30%a4%33%ca%33%2a%d7%03%00%00%00%00%49%45%4e%44%ae%42%60%82",
    throbbericon :"data:image/gif,GIF89a%0D%00%0D%00%84%1E%00%00%00%00%08%73%BD%0C%7B%BD%18%7B%C6%1C%84%C6%35%90%CA%46%9C%CE%5A%A2%D3%6B%AF%D8%8B%BF%E1%B5%B5%B5%A0%CE%E7%B5%D6%EF%BD%BD%BD%BD%DE%EF%C6%C6%C6%CE%CE%CE%D6%D6%D6%DE%DE%DE%CA%E2%F3%D6%E7%F7%DE%EF%F7%E7%E7%E7%E7%EF%F7%E7%F7%FF%EF%EF%EF%EF%F7%FF%F7%F7%F7%F7%F7%FF%F7%FF%FF%FF%FF%FF%FF%FF%FF%21%FF%0B%4E%45%54%53%43%41%50%45%32%2E%30%03%01%00%00%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%59%E0%27%7E%54%82%2C%D5%38%56%46%E0%BA%87%B6%0A%81%40%04%37%CE%89%6D%51%25%81%C4%E4%86%20%D5%2E%1E%60%C2%33%71%69%16%01%84%27%19%9C%B6%18%88%2A%75%E9%C9%26%80%52%0F%E3%C0%B0%06%18%94%E3%74%DD%0C%C8%7A%15%F6%20%2A%AA%D0%02%06%44%4B%37%BA%EC%5F%08%32%2A%24%0B%27%29%23%21%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%47%E0%27%7E%D3%92%7C%DA%A8%AE%22%37%5E%C4%17%14%47%21%16%E9%EA%71%44%30%BC%2A%4F%22%60%70%88%2E%AB%8A%4C%69%73%9C%10%A2%83%4A%BA%58%7C%A4%9F%0B%C2%35%72%4C%64%2C%91%C0%33%8A%75%59%E6%AB%ED%B3%0E%47%91%2B%E4%69%15%02%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%3F%E0%27%7E%D7%58%8D%63%89%8A%EA%77%8A%C6%CA%AD%A2%E7%4D%C2%38%7D%C1%E8%39%85%9E%C0%23%3A%B0%8C%01%02%0D%25%48%D0%10%28%55%81%F5%C9%AD%1C%BC%56%61%27%E2%A6%46%D3%98%48%63%5A%CE%56%5E%F2%28%04%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%48%E0%27%7E%54%82%8C%E8%57%A5%A2%86%0A%1F%8C%18%22%C1%A6%B6%48%C5%A8%E7%4D%9F%80%EB%73%FA%38%12%C8%84%8D%71%4A%88%9C%81%68%E0%83%44%31%0E%D8%C3%72%77%03%7E%86%A2%D5%4D%05%FB%18%8A%1F%02%67%74%61%21%C0%A3%DD%49%2C%0A%01%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%49%E0%27%7E%D3%92%7C%DA%A8%AE%22%37%5E%C4%17%14%C7%58%A4%6C%7E%E5%9F%23%EE%AA%0B%E2%E2%F1%14%7A%27%84%A8%26%48%78%6A%8B%C5%A7%F6%D9%05%02%84%A3%63%22%53%39%0A%81%8F%C0%33%8A%8D%1C%82%95%79%7A%FC%B4%79%53%60%F0%73%5A%85%00%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%40%E0%27%7E%D7%58%8D%63%89%8A%EA%77%8A%C6%57%8C%DC%BA%0E%E3%F4%05%B6%2E%78%A2%03%AA%F6%89%D9%44%09%E0%0A%21%AA%F0%2A%4A%D2%47%30%4A%04%0C%8E%5D%AB%A0%E3%10%78%A8%ED%4A%63%3A%12%51%3A%11%79%14%02%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%45%E0%27%7E%D4%87%8C%E8%57%A5%A2%86%0A%1F%8C%18%22%C1%A6%B6%58%C2%77%E0%9A%22%47%C2%81%62%9C%12%22%E4%E8%A8%4C%7E%12%9E%0F%8D%51%1A%25%02%D0%49%0B%55%B9%26%26%03%2E%8F%10%C8%11%38%A3%0B%0B%F1%43%95%4E%AB%51%08%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%46%E0%27%7E%D3%97%7C%DA%A8%AE%22%37%5E%C4%17%14%C7%58%A4%6C%7E%E5%9F%23%EE%AA%0B%02%57%E8%9D%10%A2%1A%F2%53%5B%2C%98%BD%80%00%27%72%94%02%9F%42%60%E1%19%09%BA%A2%C1%CC%E3%F1%AD%62%D9%43%31%CB%1B%1D%80%41%13%2B%04%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%41%E0%27%7E%D7%58%8D%63%89%8A%EA%77%8A%C6%57%8C%DC%BA%0E%E3%F4%05%B6%2E%78%A2%83%E8%54%FB%C4%50%9C%04%CF%06%23%F0%10%A3%19%49%14%30%50%80%1F%C7%AE%45%98%60%75%A8%16%6C%A4%31%31%8B%28%F0%A7%3C%0A%01%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%49%E0%27%7E%54%82%8C%E8%57%A5%A2%86%0A%1F%8C%18%22%C1%A6%B6%48%C5%F7%17%68%89%0F%E1%40%3C%30%50%8C%53%60%29%0A%7E%4E%CE%42%62%9A%70%88%68%8C%9D%E0%E2%F1%8C%26%AD%51%61%D5%AB%C0%3E%86%53%8D%33%BA%B0%10%AE%D4%EE%44%16%85%00%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%48%E0%27%7E%D3%92%7C%DA%A8%AE%22%37%5E%C4%17%14%C7%58%A4%63%CC%8A%97%1C%18%94%91%83%B7%F8%18%08%81%00%02%57%F8%38%4E%08%CE%E9%83%10%D5%8A%9F%83%C7%53%89%AA%1C%13%D9%EE%23%F0%E4%BE%2C%5D%B6%F9%61%8F%B3%BD%55%6F%AA%0A%01%00%21%F9%04%01%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%41%E0%27%7E%D7%58%8D%63%89%8A%EA%77%A2%C5%C8%AD%41%2C%0E%E3%C4%16%C1%22%EA%02%8F%E8%E0%71%7C%04%23%C3%CA%E3%39%AC%50%08%D6%47%23%B2%95%90%2B%63%A0%55%D0%FD%56%DC%8F%52%44%15%BD%56%B3%95%77%8A%0A%01%00%3B",
  };


  $debug = {
    verbose : 0,
    time : 0,
    time_start: undefined,
  };

}

function debug_time(msg) {
  if(!$debug.time)
    return;
  d=new Date();
  if(!$debug.time_start) {
    $debug.time_start = d.getTime();
    //GM_log('TIMESTAMP time_start is ' + $debug.time_start);
  }
  diff = (d.getTime() - $debug.time_start);
  GM_log('TIMESTAMP ' + diff + ' #' + msg);
}

function log(msg, verbose) {
  if(!verbose && !$debug.verbose)
    return;
  GM_log(msg);
}


//obsługa "admin-forward"
function process_url() {
  gotolen = $consts.admin_goto_hash.length;
  //log('hash: ' + document.location.hash.slice(0,gotolen+1) + ' ' + document.location.hash.slice(gotolen+1));

  if(document.location.hash == '#favpostok') {
    //window.location.hash = "";
    to = window.location.href.replace(/#.*/,'#');
    window.location.replace(to);
    return 1;
  }

  //jeśli właśnie weszliśmy do skrzynki odbiorczej, to nie mamy "nowej" poczty
  if(document.location.href == 'http://admin.salon24.pl/mail/') {
    //$state.newmails = 0;
    GM_setValue("newmails", 0);
  }


  if(document.location.hash.slice(0,gotolen+1) == '#' + $consts.admin_goto_hash) {
    to = document.location.hash.slice(gotolen+1);

    dest = 'back';
    if(to.indexOf(dest) == 0 && dest.length == to.length) {
      window.history.go(-2);
      return 1;
    }

    gotourl = null;

    dest = 'mail-new/';
    if(to.indexOf(dest) == 0) {
      uid = parseInt(to.slice(dest.length));
      if(!uid || uid<0)
	return -1;
      gotourl = $consts.admin_url + dest + uid;
    }

    dest = 'posts-edit/';
    if(to.indexOf(dest) == 0) {
      if(dest.length == to.length) 
	gotourl = $consts.admin_url + dest;
      else {
	pid = parseInt(to.slice(dest.length));
	if(!pid || pid<0)
	  return -1;
	gotourl = $consts.admin_url + dest + pid;
      }
    }

    if(gotourl) {
      //log('going to: ' + gotourl);
      document.location.replace(gotourl);
      //document.location.hash = $consts.admin_goto_hash + 'back';
      //document.location = gotourl;
      return 1;
    }
  }


  return 0;
}


function update_iframe() {

  if($state.blog_domain == 'admin.salon24.pl') 
    return;
  body = document.getElementById('body');
  ifr = document.createElement('iframe');
  ifr.id = 'ifr';


  body.insertBefore(ifr, body.firstChild);

  ifr.src = 'http://admin.salon24.pl/posts/';
  ifr.contentDocument.location =  'http://admin.salon24.pl/mail-new/1234';

}


function get_my_info() {
  //page load error
  if(!document.domain)
    return -1;

  var cookies = document.cookie.split(' ');
//  log(document.cookie);

  $state.blog_domain = document.domain.replace(/^www\./,'');
  log('blog domain: ' + $state.blog_domain);

  for(c=0;c<cookies.length;c++) {
    cookies[c] = cookies[c].replace(/;$/,'');
    //log('cookie: ' + cookies[c]);
  }

  for(c=0;c<cookies.length;c++) {
    cookie = cookies[c].split('=');
    if(cookie[0] == 's_us_name') {
      $state.my_domain = cookie[1];
      $state.is_logged = true;
      log('my domain: ' + $state.my_domain);
    }
  }

  postinfo = getElementByClass('post-detal',document,'div');
  if(postinfo) {
      post_id = parseInt(postinfo.id.replace(/^post-/,''));
      if(post_id >0) {
	$state.post_id = post_id;
	log('post_id: ' + $state.post_id);
      }
  }

  authorinfo = getElementByClass('ui-icon ui-icon-heart', document.getElementById('thisblog'), 'span');
  if(authorinfo) {
    blog_author_id = parseInt(authorinfo.parentNode.getAttribute('onclick').replace(/.*\(([0-9]+),.*\)/,'$1'));
    if(blog_author_id > 0) {
      $state.blog_author_id = blog_author_id;
      log('blog_author_id: ' + $state.blog_author_id);
    }
  }

  author = document.getElementById('blog-user');
  if(author) {
    h1 = author.getElementsByTagName('h1');
    if(h1.length) 
      h = h1[0];
    else
      h = author.getElementsByTagName('h2')[0];
    if(h.getElementsByTagName('a').length)
      blog_author_name = h.getElementsByTagName('a')[0].innerHTML;
    else
      blog_author_name = h.innerHTML;
    if(blog_author_name) {
      $state.blog_author_name = blog_author_name;
      log('blog_author_name: ' + $state.blog_author_name);
    }
  }
}

function count_watched(doc) {

  if(document.location.href.slice(0,$consts.watch_page_url.length) == $consts.watch_page_url) {
    if($state.watched_cache)
      newcomments = $state.watched_cache;
    else
      $state.watched_cache = newcomments = parse_watched(doc);
  } else
    newcomments = parse_watched(doc);

  serialize = "";

  $state.watched_new_answers = 0;
  for(c=0; c<newcomments.rows.length;c++) {
    $state.watched_new_answers += (newcomments.rows[c].ncomments != 0);
    if(newcomments.rows[c].ncomments)
      serialize = (serialize ? (serialize + ":") : "") + newcomments.rows[c].id + '=' + newcomments.rows[c].ncomments;
    //$state.watched_new_answers += newcomments.rows[c].ncomments;
  }
  if($state.watched_new_answers > 0) {
    $state.watched_first_link = newcomments.rows[0].link + $consts.show_last_hash + newcomments.rows[0].ncomments;
    $state.watched_first_title = newcomments.rows[0].title + ' (' + newcomments.rows[0].ncomments + ')';
    GM_setValue("watched_first_link", $state.watched_first_link);
    GM_setValue("watched_first_title", $state.watched_first_title);
  }
  GM_setValue("watched_serialize", serialize);
  GM_setValue("watched_new_answers", $state.watched_new_answers.toString());
}


function recheck_status(force) {
  //log('recheck_status @' + new Date().toTimeString());

  now = new Date().getTime();
  last_check = parseInt(GM_getValue("recheck_time", 0));
  if(force || now - last_check >= $consts.update_delay * 1000) {
    //ustaw timer od razu, żeby nie rozpocząć dwóch sprawdzań równolegle
    GM_setValue("recheck_time", now.toString());
    loadPage($consts.watch_page_url, onload_watch_page_info);
  } else {
    //GM_log("-cached-");
    $state.watched_first_link = GM_getValue("watched_first_link");
    $state.watched_first_title = GM_getValue("watched_first_title");
    $state.watched_new_answers = GM_getValue("watched_new_answers",0);
    $state.newmails = GM_getValue("newmails",0);

    update_ui();
  }
}

function loop_recheck_status() {
  recheck_status(false);

  //sprawdza czterokrotnie w ciągu update_delay (bo może inny wątek odświeżył)
  delay = $consts.update_delay * 1000 / 4;
  if(delay<1000) delay = 1000;
  setTimeout(loop_recheck_status, delay);
}

/* Przegląda zapamietane informacje o obserwowanych stronach
 * Jeśli aktualnie wszedłem na jedną ze stron obserwowanych to uznaje, że wszystkie komentarze na niej
 * zostały obejrzane, więc kasuję tę notkę z listy */
function offline_update_watched() {
  if($state.post_id) {
    serialize = GM_getValue("watched_serialize","");
    //log("serialize: " + serialize,1);
    watched = serialize.split(':');
    for(w=0, match=false, newserialize="";w<watched.length;w++){
      //log("watched: "+ watched[w],1);
      ar = watched[w].split('=');
      id = parseInt(ar[0]);
      count = parseInt(ar[1]);
      if(id == $state.post_id) 
       match = true;
      else 
	//budujemy nową listę pomijając czytaną właśnie notkę
	newserialize = (newserialize ? (newserialize + ':') : "") + watched[w];
    }
    if(match) {
      //log("newserialize: " + newserialize,1);
      //natychmiast zmieniamy to co wiemy
      GM_setValue("watched_serialize", newserialize);
      GM_setValue("watched_new_answers", watched.length-1);
      //wymusamy ponowne sprawdzenie strony obserwowanych (żeby otrzymać nowe linki/tytuły)
      recheck_status(true);
    }
      
  }
}

function get_account_info() {
  if(!$state.is_logged)
    return 0;

  if(document.location.href.slice(0,$consts.watch_page_url.length) == $consts.watch_page_url)
    analyze_watch_page_info(document);
  else 
    offline_update_watched();

  if($consts.update_delay > 0)
    loop_recheck_status();
}

function onload_watch_page_info(responseDetails) {
  xmlDoc = new DOMParser().parseFromString(responseDetails.responseText, 'text/xml');
  analyze_watch_page_info(xmlDoc);
}

function analyze_watch_page_info(doc) {
  //log("analyze_watch_page_info",1);

  count_watched(doc);
  
  tds = getElementsByClass('new_mails', doc, 'span');
  $state.newmails = tds.length;
  GM_setValue("newmails", $state.newmails.toString());

  //ustaw timer w momencie zakoćzenia sprawdzania
  GM_setValue("recheck_time", new Date().getTime().toString());
  update_ui();
}


//wersja XPath działa ładnie dla 'document', ale nie działa dla XMLa wygenerowanego z wyniku GM_xmlhttpRequest :(
function parse_watched_xpath(dom) {
  var newcomm = new Array();
  var nc = 0;

  query = "//div[@id='posts-comments-watch']//tr[@id]";
  watchrows = dom.evaluate(query, dom.documentElement, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  //watchrows = dom.evaluate(query, dom.getElementById('posts-comments-watch'), null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  log(watchrows.snapshotLength);
  for (i = 0; i < watchrows.snapshotLength; i++) {
    var row = watchrows.snapshotItem(i);
    newcomm[nc] = new Object();
    newcomm[nc].id = row.id.slice(row.id.indexOf('-')+1);
    columns = row.getElementsByTagName('td');
    info = columns[0].getElementsByTagName('a')[0];
    newcomm[nc].title = info.innerHTML;
    newcomm[nc].link = info.href;
    newcomm[nc].ncomments = parseInt(columns[3].innerHTML);
    newcomm[nc].row = row;
    
    //log('watched: ' + newcomm[nc].id + ' ' + newcomm[nc].ncomments + ' '+ newcomm[nc].link + ' ' + newcomm[nc].title);

    nc++;
  }
  return newcomm;
}

function parse_watched(dom) {
  var newcomm = new Object();
  newcomm.rows = new Array();
  newcomm.sel = new Array();
  var nc = 0;

  //wiersze tabeli z niepustą nazwą klasy
  //rows =  getElementsByCondition(function(el){if(el.className) return el;}, dom.getElementById('posts-comments-watch'), 'tr');
  rows =  dom.getElementById('posts-comments-watch').getElementsByTagName('tr');

  for (i = 0; i < rows.length; i++) {
    var row = rows[i];
    if(!row.className) 
      newcomm.header = row;
    else {
      newcomm.rows[nc] = new Object();
      newcomm.rows[nc].id = row.id.slice(row.id.indexOf('-')+1);
      columns = row.getElementsByTagName('td');
      info = columns[1].getElementsByTagName('a')[0];
      newcomm.rows[nc].title = info.innerHTML;
      newcomm.rows[nc].link = info.href;
      newcomm.rows[nc].ncomments = parseInt(columns[4].innerHTML);
      newcomm.rows[nc].xdate = Date.parse(columns[3].innerHTML.replace(/-/g,'/'));
      newcomm.rows[nc].row = row;
      //log('watched: ' + newcomm.rows[nc].id + ' ' + newcomm.rows[nc].ncomments + ' '+ newcomm.rows[nc].link + ' ' + newcomm.rows[nc].title);

      nc++;
    }
  }
  return newcomm;
}

$lprunning = 0;

function event_watched_del_done(responseDetails) {
  $lprunning--;
  log('lpdone, running: ' + $lprunning);
}

function islpdone(whendone, timeouts, wait) {
  log('timeout ' + wait + ' x ' + timeouts + ' lprunning ' + $lprunning);
  
  if(timeouts<=0 || $lprunning<=0) {
    whendone();
    return 0;
  }

  setTimeout(function () {islpdone(whendone, --timeouts, wait);}, wait);
}


function update_fck(editroInstance) {
  //fck = FCKeditorAPI.GetInstance('content-textarea');
  fck = editroInstance;
  //fck.SwitchEditMode();
  fck.Config.ToolbarSets.Default25 = fck.Config.ToolbarSets.Default.slice();
  fck.Config.ToolbarSets.Default25.push(new Array("Source"));
  fck.ToolbarSet.Load('Default25');

  if(old_FCKeditor_OnComplete) 
    old_FCKeditor_OnComplete(editroInstance);
}


function update_post_edit() {
 if(document.location.href.slice(0,$consts.postedit_page_url.length) != $consts.postedit_page_url)
    return;

  old_FCKeditor_OnComplete = undefined;
  if(unsafeWindow.FCKeditor_OnComplete)
    old_FCKeditor_OnComplete = unsafeWindow.FCKeditor_OnComplete;

  log('update_post_edit', 1);
  unsafeWindow.FCKeditor_OnComplete = update_fck;
}

function update_watched_page() {
  if(document.location.href.slice(0,$consts.watch_page_url.length) != $consts.watch_page_url)
    return;

  if(!$state.watched_cache)
    $state.watched_cache = parse_watched(document);

  for (i = 0; i < $state.watched_cache.rows.length; i++) {
    watch = $state.watched_cache.rows[i];

    //dodaj link do pierwszego niewidzianego komentarza
    if(watch.ncomments>0) {
      a = createLink(watch.link + $consts.show_last_hash + watch.ncomments, watch.ncomments);
      a.style.color = 'inherit';
      td = watch.row.getElementsByTagName('td')[4];
      td.replaceChild(a,td.firstChild)
    }


  }

  //sortowanie obserwowanych według postów *i daty powstania notki*
  //(tylko jeśli nie włączono żadnych opcji sortowania)
  if(document.location.href == $consts.watch_page_url) {
    wrsort = function (a,b) { 
      if(a.ncomments != b.ncomments)
	return b.ncomments - a.ncomments;
      else 
	return b.xdate - a.xdate;
    };

    $state.watched_cache.rows.sort(wrsort);

    watchtable = document.getElementById('posts-comments-watch').getElementsByTagName('table')[0];
    while(watchtable.rows.length>1)
      watchtable.deleteRow(1);

    tbody = watchtable.getElementsByTagName('tbody')[0];
    for (i = 0; i < $state.watched_cache.rows.length; i++) {
      $state.watched_cache.rows[i].row.className = 'r' + i%2;
      tbody.appendChild($state.watched_cache.rows[i].row);
    }
  }


}

function update_post_permalink() {
  //łatwy dostęp do permalinku gdy adresem notki jest adres bloga
  if(document.location.pathname == '/') {

    last_posts = document.getElementById('my-last-posts');
    if(!last_posts) return;
   
    li = last_posts.getElementsByTagName('li');
    if(!li) return;

    h2 = li[0].getElementsByTagName('h2');
    if(!h2) return;

    a = h2[0].getElementsByTagName('a');
    if(!a) return;

    title = a[0].innerHTML;
    link  = a[0].href;

    h1 = document.getElementById('post-' + $state.post_id).getElementsByTagName('h1');
    if(!h1) return;

    posttitle = h1[0].innerHTML;
    if(title == posttitle) {
      ta = createLink(link,posttitle);
      ta.style.color = 'inherit';
      ta.style.textDecoration = 'none';
      h1[0].replaceChild(ta, h1[0].firstChild);
    }
  }
}

function update_post() {
  //dodaj możliwośc wysłania wiadomości do właściciela bloga i banowania autora
  if($state.blog_author_id) {
    rightcolumn = getElementByClass('content-right',document.getElementById('content'),'div');
    mailto = createLink($consts.admin_goto_url + 'mail-new/' + $state.blog_author_id, 'wyślij wiadomość do autora bloga');
    mailto.style.backgroundImage = 'url(http://s.salon24.pl/admin/gfx/icons.gif)';
    mailto.style.backgroundPosition = 'left -87px';
    mailto.style.backgroundRepeat = 'no-repeat';
    mailto.style.paddingLeft = '20px';
    //mailto.style.textDecoration = 'none';
    mailto.innerHTML='wyślij wiadomość do autora';

    ban = createLink('#lock-user-' + $state.blog_author_id, 'zablokuj autora na swoim blogu');
    ban.title = 'dodaj do listy zablokowanych użytkowników';
    ban.style.backgroundImage = 'url(' + $media.lock + ')';
    //ban.style.backgroundPosition = 'left -63px';
    ban.style.backgroundRepeat = 'no-repeat';
    ban.style.paddingLeft = '20px';
    //ban.style.textDecoration = 'none';
    ban.setAttribute('user_to_lock', $state.blog_author_id);
    addEvent(ban, 'click', function(e) { id=this.getAttribute('user_to_lock'); unsafeWindow.Service.lockUserPopup(id); e.preventDefault(); } );


    div = document.createElement('div');
    div.className = 'box';
    div.appendChild(mailto);
    div.appendChild(document.createElement('br'));
    div.appendChild(ban);

    rightcolumn.appendChild(div);
  }

  //podmień obsługę 'dodaj do obserwowanych'
  if($state.post_id) {
    $state.add_to_fav = getElementByClass('ico_add_to_favorite', document, 'a');
    if($state.add_to_fav) {
      $state.add_to_fav.removeAttribute('onclick');
      addEvent($state.add_to_fav, 'click', function(e) { event_add_fav_post($state.post_id); e.preventDefault(); } );
    }
  }

	update_post_permalink();
}

// misc functions
//
function $elem(tag, params, childNodes) { 
  if(typeof(childNodes)=='undefined') childNodes = [];

  var ret = document.createElement(tag);
  for(var param in params) {
    if(typeof(params[param])=='string') {
      ret[param] = params[param];
    } else {
      for(var k in params[param]) {
        ret[param][k] = params[param][k];
      }
    }
  }

  for(var i=0;i<childNodes.length;i++) {
    ret.appendChild(childNodes[i]);
  }

  return ret;
}

function parseHtmlResponse(response) {

	response = response.responseText.split('\n');
	var res = [];
	for(var i=0;i<response.length;i++) {
		if(response[i].match('<body.*>')) {
			i++;
			break;
		}
	}

	for(;i<response.length;i++) {
		if(response[i].match('</body>')) break;
		res[res.length] = response[i];
	}

	res = res.join('\n');
	var div = document.createElement('div');
	div.innerHTML = res;

	return div;
}

function super_hack() {
  var x = document.createElement('script');
  x.type = "text/javascript";
  x.src = chrome.extension.getURL('script.js');
  document.head.appendChild(x);
}

var gvar=function() {} // Global variables
function GM_ApiBrowserCheck() {
  const GMSTORAGE_PATH = 'GM_'; // You can change it to avoid conflict with others scripts
  if(typeof(unsafeWindow)=='undefined') { unsafeWindow=window; }
  if(typeof(GM_log)=='undefined') { GM_log=function(msg) { try { unsafeWindow.console.log('GM_log: '+msg); } catch(e) {} }; }
  GM_clog=function(msg) { if(arguments.callee.counter) { arguments.callee.counter++; } else { arguments.callee.counter=1; } GM_log('('+arguments.callee.counter+') '+msg); }
  GM_addGlobalStyle=function(css) { // Redefine GM_addGlobalStyle with a better routine
    var sel=document.createElement('style'); sel.setAttribute('type','text/css'); sel.appendChild(document.createTextNode(css));
    var hel=document.documentElement.firstChild; while(hel && hel.nodeName!='HEAD') { hel=hel.nextSibling; }
    if(hel && hel.nodeName=='HEAD') { hel.appendChild(sel); } else { document.body.insertBefore(sel,document.body.firstChild); }
    return sel;
  }
  var needApiUpgrade=false;
  if(window.navigator.appName.match(/^opera/i) && typeof(window.opera)!='undefined') {
    needApiUpgrade=true; gvar.isOpera=true; GM_log=window.opera.postError; GM_log('Opera detected...');
  }
  if(typeof(GM_setValue)!='undefined') {
    var gsv=GM_setValue.toString();
    if(gsv.indexOf('staticArgs')>0) { gvar.isGreaseMonkey=true; GM_log('GreaseMonkey Api detected...'); } // test GM_hitch
    else if(gsv.match(/not\s+supported/)) { needApiUpgrade=true; gvar.isBuggedChrome=true; GM_log('Bugged Chrome GM Api detected...'); }
  } else { needApiUpgrade=true; GM_log('No GM Api detected...'); }

  if(needApiUpgrade) {
    GM_log('Try to recreate needed GM Api...');
    var ws=null; try { ws=typeof(unsafeWindow.localStorage); unsafeWindow.localStorage.length; } catch(e) { ws=null; } // Catch Security error
    if(ws=='object') {
      GM_log('Using localStorage for GM Api.');
      GM_getValue=function(name,defValue) { var value=unsafeWindow.localStorage.getItem(GMSTORAGE_PATH+name); if(value==null) { return defValue; } else { switch(value.substr(0,2)) { case 'S]': return value.substr(2); case 'N]': return parseInt(value.substr(2)); case 'B]': return value.substr(2)=='true'; } } return value; }
      GM_setValue=function(name,value) { switch (typeof(value)) { case 'string': unsafeWindow.localStorage.setItem(GMSTORAGE_PATH+name,'S]'+value); break; case 'number': if(value.toString().indexOf('.')<0) { unsafeWindow.localStorage.setItem(GMSTORAGE_PATH+name,'N]'+value); } break; case 'boolean': unsafeWindow.localStorage.setItem(GMSTORAGE_PATH+name,'B]'+value); break; } }
      GM_deleteValue=function(name) { unsafeWindow.localStorage.removeItem(GMSTORAGE_PATH+name); }
    } else if(!gvar.isOpera || typeof(GM_setValue)=='undefined') {
      GM_log('Using temporarilyStorage for GM Api.'); gvar.temporarilyStorage=new Array();
      GM_getValue=function(name,defValue) { if(typeof(gvar.temporarilyStorage[GMSTORAGE_PATH+name])=='undefined') { return defValue; } else { return gvar.temporarilyStorage[GMSTORAGE_PATH+name]; } }
      GM_setValue=function(name,value) { switch (typeof(value)) { case "string": case "boolean": case "number": gvar.temporarilyStorage[GMSTORAGE_PATH+name]=value; } }
      GM_deleteValue=function(name) { delete gvar.temporarilyStorage[GMSTORAGE_PATH+name]; };
    }
    if(typeof(GM_openInTab)=='undefined') { GM_openInTab=function(url) { unsafeWindow.open(url,""); } }
    if(typeof(GM_registerMenuCommand)=='undefined') { GM_registerMenuCommand=function(name,cmd) { GM_log("Notice: GM_registerMenuCommand is not supported."); } } // Dummy
    if(!gvar.isOpera || typeof(GM_xmlhttpRequest)=='undefined') {
      GM_log('Using XMLHttpRequest for GM Api.');
      GM_xmlhttpRequest=function(obj) {
        var request=new XMLHttpRequest();
        request.onreadystatechange=function() { if(obj.onreadystatechange) { obj.onreadystatechange(request); }; if(request.readyState==4 && obj.onload) { obj.onload(request); } }
        request.onerror=function() { if(obj.onerror) { obj.onerror(request); } }
        try { request.open(obj.method,obj.url,true); } catch(e) { if(obj.onerror) { obj.onerror( {readyState:4,responseHeaders:'',responseText:'',responseXML:'',status:403,statusText:'Forbidden'} ); }; return; }
        if(obj.headers) { for(name in obj.headers) { request.setRequestHeader(name,obj.headers[name]); } }
        request.send(obj.data); return request;
  } } }
}


//// salon 2.0 import
function getElementsByCondition(condition,container,tag) {
  container = container||document;
  tag = tag||'*';
  var all = container.all||container.getElementsByTagName(tag);
  var arr = [];
  for(var k=0;k<all.length;k++) {
    var elm = all[k];
    if(condition(elm,k)) arr[arr.length] = elm;
  }
  return arr;
} 

function getElementsByClass(classname, container, tag) {
  var re = new RegExp('\\b'+classname+'\\b');
  return getElementsByCondition(function(el){if(el.className && el.className.match(re)) return el;}, container, tag);
}

function getElementByClass(classname, container, tag) {
  var re = new RegExp('\\b'+classname+'\\b');
  var ret = getElementsByCondition(function(el){if(el.className && el.className.match(re)) return el;}, container, tag);
  if(ret.length>0) return ret[0];
}
function addEvent(obj, evType, fn) {
  if(!obj) return false;
  if (obj.addEventListener) {
    obj.addEventListener(evType, fn, false);
    return true;
  } else if (obj.attachEvent) {
    var r = obj.attachEvent("on" + evType, fn);
    return r;
  } else {
    return false;
  }
}

function loadPage(address, onLoad, onError) {
  //log('GM_xmlhttpRequest(' + address + ')');
  GM_xmlhttpRequest({
    method: 'GET',
    url: address,
    headers: {
      'Cookie': document.cookie,
      //'Accept-Charset': 'ISO-8859-2',
      'X-Requested-With': 'XMLHttpRequest',
    },
    onload: function(responseDetails) {
      //log('status:' + responseDetails.status);
      if(responseDetails.status != 200) {
	//hideLoadingInfo();
	log('status:\n' + responseDetails.status);
	log('statustext:\n'+responseDetails.statusText);
	log('responsetext:\n'+responseDetails.responseText);
	return;
      }	

      if(onLoad) onLoad(responseDetails);
    },
    onerror: function(responseDetails) {
      log('status:\n' + responseDetails.status);
      log('statustext:\n'+responseDetails.statusText);
      log('responsetext:\n'+responseDetails.responseText);
      //hideLoadingInfo();
      if(onError) onError(responseDetails);
    }
  });
}


////
function update_ui() {
  update_ui_watched();
  update_ui_newmails();
}

function update_ui_watched() {
  log('new answers: ' + $state.watched_new_answers);
  if(!$state.watched_link)
    return;
  if($state.watched_new_answers > 0) {
    //$state.watched_link.innerHTML = 'obserwowane ('+ $state.watched_new_answers + ')';
    $state.watched_link.style.color='red';
    $state.watchedcount_link.innerHTML = '('+ $state.watched_new_answers + ')';
    $state.watchedcount_link.href = $state.watched_first_link;
    $state.watchedcount_link.title = $state.watched_first_title;
    $state.watchedcount_link.style.display ='inline';
  } else {
    $state.watched_link.innerHTML = 'Obserwowane';
    $state.watched_link.style.color='';
    $state.watchedcount_link.style.display ='none';
  }
}

function update_ui_newmails() {
  log('new mails: ' + $state.newmails);
  if(!$state.newmails_li)
    return;
  if($state.newmails > 0)
    $state.newmails_li.style.display = 'list-item';
  else
    $state.newmails_li.style.display = 'none';
}


function createLink(url, text) {
  a = document.createElement('a');
  a.href = url;
  a.innerHTML = text;
  return a;
}

function update_filters() {
  if(GM_getValue('filter_unlock', false)) {
    change_filter(1, true); 
    change_filter(2, true); 
  } else {
    change_filter(1, get_filter(1));
    change_filter(2, get_filter(2));
  }
}


function apply_menu_look() {
  menu = document.getElementById('service-navi');
  if(!menu) return 1;

  hide_start = GM_getValue("titlebar_hide_start", false);
  hide_catalogs = GM_getValue("titlebar_hide_catalogs", false);
  shorten = GM_getValue("titlebar_shorten", false)

  dmn = $state.default_menu_names;

  for(i=0; i<menu.childNodes.length; i++) {
    if(!menu.childNodes[i].firstChild) continue;

    label = menu.childNodes[i].firstChild.innerHTML;
    el = menu.childNodes[i];
    id = el.id;

    if(id == 'service-navi-sg') el.style.display = hide_start ? 'none' : "";
    //if(id == 'service-navi-catalog') el.style.display = hide_catalogs ? 'none' : "";
    if(id == 'service-navi-blog-catalog') el.style.display = hide_catalogs ? 'none' : "";
    if(id == 'service-navi-np') el.style.display = hide_catalogs ? 'none' : "";
    if(id == 'service-navi-np-catalog') el.style.display = hide_catalogs ? 'none' : "";
    if(id == 'service-navi-myblog') el.style.borderLeft = hide_catalogs ? 'medium none' : "";
    if(id == 'service-navi-register') el.style.borderLeft = hide_catalogs ? 'medium none' : "";
    if(id == 'service-navi-sg') el.firstChild.innerHTML = shorten ? "SG" : dmn.servicenavisg;
    if(id == 'service-navi-manage') el.firstChild.innerHTML = shorten ? "Zarządzaj" : dmn.servicenavimanage;
    if(id == 'service-navi-disc') el.firstChild.innerHTML = shorten ? 'Dyskusje' : dmn.servicenavidisc;
    if(id == 'service-navi-catalog') el.firstChild.innerHTML = shorten ? 'Blogi' : dmn.servicenavicatalog;
    if(id == 'service-navi-blog-catalog') el.firstChild.innerHTML = shorten ? 'Blogi' : dmn.servicenaviblogcatalog;
    if(id == 'service-navi-np-catalog') el.firstChild.innerHTML = shorten ? 'Kat. lubczy' : dmn.servicenavinpcatalog;
  }
}

function update_menu() {

  menu = document.getElementById('service-navi');
  if(!menu) return 1;

  //zapamietaj domyślne nazwy w oryginalnym menu
  //znajdź "Logout" w menu i zapamiętaj
  for(i=0; i<menu.childNodes.length; i++) {
    if(!menu.childNodes[i].firstChild) continue;
    label = menu.childNodes[i].firstChild.innerHTML;
    el = menu.childNodes[i];
    id = el.id;

    eval("$state.default_menu_names." + id.replace(/-/g,'') + "=\"" + label + "\"");
    if(id == 'service-navi-logout') 
      menu_logout = el;
  }

  apply_menu_look();


  //dodaj 'obserwowane' do menu
  if($state.my_domain && menu_logout) {
    //deayed add to menu - otherwise endless loop in for
    watched = document.createElement('li');
    watched.style.display = 'list-item';
    $state.watched_link = createLink('http://admin.salon24.pl/posts-comments-watch/', 'obserwowane');
    $state.watchedcount_link = createLink('http://admin.salon24.pl/posts-comments-watch/', '(0)');
    $state.watchedcount_link.style.display = 'none';
    $state.watchedcount_link.style.color='red';
    //jeśli nowy komentarz jest w tej samej notce i nie zmienia się URL, to trzeba oświerzyć stronę - inaczej ani komentarz nie będzie widoczny, ani nie zadziała #show-laet-
    addEvent($state.watchedcount_link, 'click', function(e) { if(this.href.split('#')[0] == document.location.href.split('#')[0]) { e.preventDefault(); document.location.href = this.href; document.location.reload(); }} );
    watched.appendChild($state.watched_link);
    watched.appendChild(document.createTextNode(' '));
    watched.appendChild($state.watchedcount_link);
    update_ui_watched();

    $state.newmails_li = document.createElement('li');
    $state.newmails_li.style.display = 'list-item';
    link = createLink('http://admin.salon24.pl/mail/', 'nowa poczta');
    link.style.color = 'red';
    $state.newmails_li.appendChild(link);
    //przejmij obsługe informacji o nowej poczcie od skryptu salonowego (nasza lepsza - live update)
    unsafeWindow.Service.checkNewMailsShow = function () { if (this.checkNewMailsCnt){ if(!$state.newmails) $state.newmails = this.checkNewMailsCnt; update_ui_newmails(); }};
    update_ui_newmails();

    menu.insertBefore($state.newmails_li, menu_logout);
    menu.insertBefore(watched, menu_logout);
  }
  

  if(GM_getValue("floating_top_menu",0)) {
    sh = document.getElementById('service-header');
    sh.style.position = 'fixed';
    sh.style.width = '810px';
    //sh.style.backgroundColor = 'black';
    
    bsh = document.createElement('div');
    bsh.style.position = 'fixed';
    bsh.style.width = '100%';
    bsh.style.height = '30px';
    bsh.style.left = '0px';
    bsh.style.backgroundColor = 'black';
    sh.parentNode.insertBefore(bsh,sh);

    bh = document.getElementById('blog-header');
    bh.style.paddingTop = '30px';
  }

}

function delete_comment(my, comment, link) {
  var id = get_comment_id(comment);

  if(link.style.color!='red') {
    link.innerHTML = 'na pewno skasować?'; 
    link.style.color='red';
    return 0;
  }
 
  var url;
  if(my)
    url = 'http://admin.salon24.pl/comments-my-delete-json/' +id;
  else
    url = 'http://admin.salon24.pl/comments-delete-json/' + id;

  loadPage(url,
      function (responseDetails) { 
	//log('skasowano');
        link.innerHTML = 'skasowany';
	comment.style.display = 'none';
	return 0;
      },
      function (responseDetails) {
        link.innerHTML = 'nie udało się skasować';
	return 0;
      }
 );
}

function get_comment_id(comment) {
  for(f=0;f<comment.childNodes.length;f++) {
    field = comment.childNodes[f];
    if(field.nodeName == "A" && field.name) {
      commentname = field.name;
      u = commentname.indexOf('_');
      commentid = commentname.slice(u+1);
      break;
    }
  }
  return commentid;
}

function get_comment_form(id) {
  if(id)
    form = document.getElementById('comment_form-add_comment_form-' + id);
  else 
    form = document.getElementById('comment_form-add_comment_form');
  return form;
}

function get_comment_message(form,id) {
  if(!form) return null;
  ta = form.getElementsByTagName('textarea');
  for(input=null,i=0;i<ta.length;i++) {
    if(ta[i].name == 'message') {
      input = ta[i];
      break;
    }
  }
  return input;
}

function get_comment_title(form,id) {
  if(!form) return null;
  inputs = form.getElementsByTagName('input');
  for(i=0;i<inputs.length;i++) {
    if(inputs[i].name == 'title'){ 
      input = inputs[i];
      break;
    }
  }
  return input;
}

function quote_comment(id) { 
  form = get_comment_form(id);
  input = get_comment_message(form, id);
  
  cid='comment-body-' + id;
  q=document.getElementById(cid).innerHTML; 
  if(q && q.length) 
    input.value = $consts.quote_start + q.replace(/<br>/g,'') + $consts.quote_end + input.value;
}


function quote_sel(id) {
  form = get_comment_form(id);
  input = get_comment_message(form, id);
  if(!input) return;

  sel = window.getSelection().toString();
  if(sel.length) input.value = $consts.quote_start + sel.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;') + $consts.quote_end + input.value;
}

function preview_comment(id) {
  log('preview_comment ' + id);
  form = get_comment_form(id);

  if(form.nextSibling && form.nextSibling.id=='comment-preview-' + id) {
    ct = document.getElementById('comment-preview-title-' + id);
    cb = document.getElementById('comment-preview-body-' + id);
  } else {

    //okno podglądu
    prwindow = document.createElement('div');
    prwindow.id = 'comment-preview-' + id;
    //prwindow.style.width = '470px';
    prwindow.style.width = '578px';
    prwindow.style.background  = '#eee';
    prwindow.style.marginLeft  = '-11px';
    prwindow.style.marginBottom  = '5px';
    prwindow.style.border = '1px solid #f55';
    //prwindow.style.display = 'none';

    ct = document.createElement('h3');
    ct.className = 'comment-title';
    ct.id = 'comment-preview-title-' + id;

    cb = document.createElement('p');
    cb.className = 'comment-body';
    cb.id = 'comment-preview-body-' + id;

    prwindow.appendChild(ct);
    prwindow.appendChild(cb);

    form.parentNode.appendChild(prwindow);
  }

  title = message = "";

  input = get_comment_title(form, id);
  if(input) title = input.value;
  input = get_comment_message(form, id);
  if(input) message = input.value;

  ct.innerHTML = title;
  cb.innerHTML = message.replace(/\n/g,'<br>');
}

function ev_quote_comment(e) {
  quote_comment(parseInt(this.parentNode.id.slice(8)));
  e.preventDefault();
}

function ev_quote_sel(e) {
  quote_sel(parseInt(this.parentNode.id.slice(8)));
  e.preventDefault();
}
function ev_preview_comment(e) {
  preview_comment(parseInt(this.parentNode.id.slice(8)));
  e.preventDefault();
}




function update_comment(comment) {

  //'zablokuj' [komentatora] na obcych blogach
  if(comment.script_tag && comment.author_id && $state.blog_domain != $state.my_domain) {
    alock = createLink('#lock-user-' + comment.author_id, 'zablokuj');
    alock.title = 'dodaj do listy zablokowanych użytkowników';
    alock.setAttribute('user_to_lock', comment.author_id);
    addEvent(alock, 'click', function(e) { /* id = parseInt(this.href.slice(this.href.indexOf('#')+11))); */ id=this.getAttribute('user_to_lock'); unsafeWindow.Service.lockUserPopup(id); e.preventDefault(); } );
    spanlock = document.createElement('span');
    spanlock.appendChild(alock);
    comment.script_tag.parentNode.insertBefore(spanlock, comment.script_tag);
  }

  //'mailto'
  if(comment.nick_tag && comment.author_id) {
    //dodaj ikonkę 'wyslij wiadomość'
    mailto = createLink($consts.admin_goto_url + 'mail-new/' + comment.author_id, ' ');
    mailto.title = 'wyślij wiadomość do autora komentarza';
    mailto.style.backgroundImage = 'url(http://s.salon24.pl/admin/gfx/icons.gif)';
    mailto.style.backgroundPosition = '4px -87px';
    mailto.style.backgroundRepeat = 'no-repeat';
    mailto.style.paddingLeft = '20px';
    
    span = document.createElement('span');
    span.className = 'le';
    span.appendChild(document.createTextNode('|'));
    span.appendChild(mailto);
    span.appendChild(document.createTextNode('|'));


    comment_date = comment.nick_tag.firstChild;
    while(comment_date && (comment_date.nodeType != 1 || comment_date.className!='le comment-date')) comment_date = comment_date.nextSibling; //firefox 3.0 nie ma firstElementChild
    comment.nick_tag.insertBefore(span,comment_date.nextSibling);
  }

  if(comment.navi_tag) {

    if(0) {
      clink = canswer = null;
      for(n=0;n<comment.navi_tag.childNodes.length;n++) {
	switch(comment.navi_tag.childNodes[n].innerHTML) {
	  case 'link do komentarza': clink = comment.navi_tag.childNodes[n]; break;
	  case 'odpowiedz': canswer = comment.navi_tag.childNodes[n]; break;
	}
      }
    } else {
      clink = comment.navi_tag.firstChild;
      while(clink && clink.nodeType != 1) clink = clink.nextSibling; //firefox 3.0 nie ma firstElementChild
      canswer = comment.navi_tag.lastChild;
      while(canswer && canswer.nodeType != 1) canswer = canswer.previousSibling; //firefox 3.0 nie ma lastElementChild
    }

    //podmień obsługę 'odpowiedz' na własną
    if(canswer) {
      comment.comment_text_tag.id = 'comment-body-' + comment.commentid;
      canswer.setAttribute('commentid', comment.commentid);
      canswer.setAttribute('author_nick', comment.author_nick);
    }

  }
}

function comment_add_buttons_html(html) {

  if(html.indexOf('preview_comment')==-1) {
    id=$cid;
    buttons = "";
    if(id)
      buttons += "<a style='margin-right: 1em;' class='button_cancel' onclick='quote_comment(" + id + "); return false;' href='#'>cytuj komentarz</a>";
    buttons += "<a style='margin-right: 1em;' class='button_cancel' onclick='quote_sel(" + id + "); return false;' href='#'>cytuj zaznaczenie</a>";
    buttons += "<a style='margin-right: 1em;' class='button_cancel' onclick='preview_comment(" + id + "); return false;' href='#'>podgląd</a>";

    buttons_start = '<p class="buttons">';
    idx = html.indexOf(buttons_start);
    if(idx!=-1)
      html = html.slice(0,idx + buttons_start.length).concat(buttons, html.slice(idx + buttons_start.length));
  }

}

function comment_add_buttons(postbuttons) {
  //cytuj komentarz
  quote = createLink('#', 'cytuj komentarz');
  quote.style.marginRight='1em';
  //quote.style.display = 'none';
  quote.id = 'quote-comment-button';
  quote.className = 'button_cancel';
  addEvent(quote, 'click', ev_quote_comment);

  //cytuj zaznaczenie
  quotesel = createLink('#', 'cytuj zaznaczenie');
  quotesel.style.marginRight='1em';
  quotesel.className = 'button_cancel';
  addEvent(quotesel, 'click', ev_quote_sel);

  //podgląd
  preview = createLink('#', 'podgląd');
  preview.style.marginRight='1em';
  preview.className = 'button_cancel';
  addEvent(preview, 'click', ev_preview_comment);

  postbuttons.insertBefore(preview,postbuttons.firstChild);
  postbuttons.insertBefore(quotesel,postbuttons.firstChild);
  postbuttons.insertBefore(quote,postbuttons.firstChild);
}



function patched_addComment(_selector, _item_oid, _default_title) {
  if(_selector == '#add_comment_form')
    id = 0;
  else 
    id = parseInt(_selector.split('-')[1]);
  log('patched_addComment ' + id);

  ret = orig_addComment(_selector, _item_oid, _default_title);
  
  form = get_comment_form(id);
  p = form.getElementsByTagName('p');
  for(buttons = null,ip=0;ip<p.length;ip++){
    if(p[ip].className=='buttons')
      buttons = p[ip];
  }
  if(!buttons) return ret;

  buttons.id = 'buttons-' + id;
  comment_add_buttons(buttons);

  return ret;
}


function add_buttons() {
  orig_addComment = unsafeWindow.Service.addComment;
  unsafeWindow.Service.addComment = patched_addComment;
}



function update_comments() {
  
  debug_time('2.1');

  //extend_comment_form();
  debug_time('2.2');
  $debug.time_start = new Date().getTime();
  debug_time('2.2x');

  cinfo = parse_comments();
  if(!cinfo) return -1;
  debug_time('2.3');
  $debug.time_start = new Date().getTime();
  debug_time('2.3x');

  add_buttons();

  for(c=0;c<cinfo.length;c++)
    update_comment(cinfo[c]);

  debug_time('2.4');
  update_comments_jumpto(cinfo);
  
  debug_time('2.5');

  post_comment = getElementByClass('ico_write_comm', document, 'a');
  if(post_comment)
    post_comment.setAttribute('onclick', post_comment.getAttribute('onclick').replace(/(\);return false;)/, ', "@' + $state.blog_author_name + '"$1'));
 
  return 0;
}

function parse_comments() {

  ul = getElementByClass('comments-list',document,'ul');
  if(!ul) return null;

  comments = ul.childNodes;

  cinfo = new Array();

  //log('have ' + comments.length + ' comments');
  for(comment_no=0,child=0;child<comments.length;child++) {
    if(comments[child].className != 'comment' && comments[child].className != 'comment ')
      continue;

    cinfo[comment_no] = new Object();

    comment = cinfo[comment_no];
    comment.li = comments[child];

    //log('next comment have ' + comments[child].childNodes.length + ' fields');
    for(f=0;f<comments[child].childNodes.length;f++) {
      field = comments[child].childNodes[f];
      //log('name ' + field.nodeName);
      if(field.nodeName == "A" && field.name) {
	comment.commentname = field.name;
	u = comment.commentname.indexOf('_');
	comment.commentid = comment.commentname.slice(u+1);
	//log('comment ' + comment.commentname + ' id ' + comment.commentid);

      }
      if(field.className=='author') {
	//comment.nick_tag = getElementByClass('author-nick', field); 
	//speedup
	comment.nick_tag = field.firstChild;
	while(comment.nick_tag && comment.nick_tag.nodeType != 1) comment.nick_tag = comment.nick_tag.nextSibling; //firefox 3.0 nie ma firstElementChild
	if(comment.nick_tag.nodeName == 'IMG') {
	  comment.nick_tag = comment.nick_tag.nextSibling;
	  while(comment.nick_tag && comment.nick_tag.nodeType != 1) comment.nick_tag = comment.nick_tag.nextSibling; //firefox 3.0 nie ma nextElementSibling
	}
	comment.author_domain = comment.nick_tag.host;
	comment.author_nick = comment.nick_tag.innerHTML;

	comment.script_tag = field.getElementsByTagName('script')[0];
	//comment.author_id = parseInt(comment.script_tag.innerHTML.slice(21,-2));
	comment.author_id = parseInt(comment.script_tag.innerHTML.replace(/.*\(([0-9]*)\);/,'$1'));
      }

      if(field.className=='comment-body')
	comment.comment_text_tag = field;

      if(field.className=='comment-navi')
	comment.navi_tag = field;

    }
    comment_no++;
  }

  return cinfo;
}

//process jump to comment directive (#show-last-n)
function update_comments_jumpto (cinfo) {
  if(!cinfo.length) {
    GM_log("No comments available");
    return;
  }

  if(document.location.hash.indexOf($consts.show_last_hash) != 0)
    return;
  
  //log(document.location.hash);
  jumpto = cinfo.length - parseInt(document.location.hash.slice($consts.show_last_hash.length));
  
  //document.location.hash = cinfo[jumpto].commentname;
  //log(document.location.href.split('#')[0] + '#' +  cinfo[jumpto].commentname);
  document.location.replace(document.location.href.split('#')[0] + '#' +  cinfo[jumpto].commentname);
}

function update_footer() {
  footerlinks = document.getElementById('footer-links');
  if(footerlinks) {
    //about = createLink($consts.project_url, $appname);
    about = createLink('http://admin.salon24.pl/#salon25', $appname);
    about.title = $appname + ', ver. ' + $version + ' - konfiguracja';
    about.style.color = 'red';
    footerlinks.appendChild(document.createTextNode(" |\u00a0 "));
    footerlinks.appendChild(about);

    footerlinks.style.width='550px';
  }
}


function event_add_fav_post(postid) {
  //log('GM_xmlhttpRequest(' + address + ')');
  address = 'http://' + $state.blog_domain + '/favorite-post-add/';
  data = 'post_oid=' + postid;

  /*
  if($state.add_to_fav) {
    $state.add_to_fav.style.backgroundImage = 'url(' + $media.throbbericon + ')';
    $state.add_to_fav.style.backgroundRepeat = 'no-repeat';
    $state.add_to_fav.style.paddingLeft = '16px';
    $state.add_to_fav.style.backgroundPosition = 'left 3px';
  }
  */

  postPage(address, data, lp_add_fav_post_ok, lp_add_fav_post_err);
}

function lp_add_fav_post_ok(responseDetails) {
  log(responseDetails.responseHeaders);
  add_fav_post_done(responseDetails.finalUrl.slice(-5) != '/404/');
}

function lp_add_fav_post_err(responseDetails) {
  log(responseDetails.responseHeaders);
  add_fav_post_done(false);
}

function add_fav_post_done(success) {
  if($state.add_to_fav) {
    if(success) {
      $state.add_to_fav.style.color = 'green';
      $state.add_to_fav.innerHTML = 'dodany do obserwowanych';
    }
    else {
      $state.add_to_fav.style.color = 'red';
      $state.add_to_fav.innerHTML = 'nie udane dodanie do obserwowanych';
    }
  }
}


function update_tag_page() {
  if(document.location.pathname.slice(0,5) == '/tag/') {
    tag = document.getElementsByTagName('h1')[0];
    h3 = document.getElementsByTagName('h3')[0];
    if(h3.innerHTML == 'moje tagi') {
      link = document.createElement('a');
      link.href=document.location.href.replace(new RegExp('//.*\.(salon24\.pl/.*)'),'//www.$1');
      link.innerHTML = "tag \"" + tag.innerHTML + "\" w całym serwisie &raquo;";
      h3.parentNode.insertBefore(link,h3.nextSibling.nextSibling.nextSibling);
    }
  }
}

function postPage(address, data, onLoad, onError) {
  //log('GM_xmlhttpRequest(' + address + ')');
  GM_xmlhttpRequest({
    method: 'POST',
    url: address,
    data : data,
    headers: {
      'Cookie': document.cookie,
      //'Accept-Charset': 'ISO-8859-2',
//      'X-Requested-With': 'XMLHttpRequest',
      'Content-type' : 'application/x-www-form-urlencoded',
    },
    onload: function(responseDetails) {
      //log('status:' + responseDetails.status);
      //log('finalUrl: '+responseDetails.finalUrl);
      if(responseDetails.status != 200) {
	//hideLoadingInfo();
	log('status: ' + responseDetails.status);
	log('statustext:\n'+responseDetails.statusText);
	log('responsetext:\n'+responseDetails.responseText);
	return;
      }	

      if(onLoad) onLoad(responseDetails);
    },

    onerror: function(responseDetails) {
      log('status:\n' + responseDetails.status);
      log('statustext:\n'+responseDetails.statusText);
      log('responsetext:\n'+responseDetails.responseText);
      //hideLoadingInfo();
      if(onError) onError(responseDetails);
    }
  });
}

function update_div(nver) {

  div = document.createElement('div');
  div.id = 'verupdate';
  ln1 = document.createElement('span');
  ln1.style.fontWeight='bold';
  ln1.appendChild(document.createTextNode('Uwaga, pojawiła się nowsza wesja skryptu Salon25'));
  ln1.appendChild(document.createElement('br'));
  ln2 = document.createElement('span');
  ln2.appendChild(document.createTextNode('Aktualnie używasz wersji: ' + $version + ', a najnowasza wersja to ' + nver));
  ln2.appendChild(document.createElement('br'));
  ln2.appendChild(document.createElement('br'));
  ln3 = document.createElement('span');
  ln3.appendChild(document.createElement('br'));
  ln3.appendChild(document.createTextNode('Zobacz '));
  ln3.appendChild(createLink($consts.project_url, 'stronę projektu Salon25'));
  ln3.appendChild(document.createTextNode(' żeby zobaczyć co się zmieniło.'));
  ln3.appendChild(document.createElement('br'));
  ln3.appendChild(document.createElement('br'));
  ln4 = document.createElement('span');
  ln4.appendChild(createLink('http://salon25.googlecode.com/svn/tags/v' + nver + '/salon25.user.js', 'Zaktualizuj do najnowszej wersji'));
  ln4.appendChild(document.createElement('br'));
  ln5 = document.createElement('div');
  ln5.style.textAlign = 'right';
  link = createLink('#', 'Zamknij okno');
  addEvent(link, 'click', function(e) { document.getElementById("verupdate").style.display="none"; e.preventDefault(); } );
  ln5.appendChild(link);
  ln5.appendChild(document.createElement('br'));

  div.appendChild(ln1);
  div.appendChild(ln2);
  div.appendChild(ln4);
  div.appendChild(ln3);
  div.appendChild(ln5);

  div.style.position = 'fixed';
  div.style.padding = '1em';
  div.style.backgroundColor = '#ffcccc';
  div.style.border = '2px solid red';
  div.style.top = '2em';
  div.style.left = '2em';

  document.getElementsByTagName('body')[0].appendChild(div);
}

function versionToInt(ver) {
  a = ver.split('.');
  return a[0] * 1000000 + a[1] * 1000 + a[2] * 1;
}

function onload_version_check_notify(responseDetails) {
  nver = responseDetails.responseText;
  GM_log("Current version is: " + $version + " (" + versionToInt($version) + ")");
  GM_log("Newest version is: " + nver + " (" + versionToInt(nver) + ")");
  if(versionToInt(nver) > versionToInt($version))
    update_div(nver);
}

function check_updates(force_check, action) {
  
  d=new Date();
  now = d.getTime();
  
  if(force_check)
    check = true;
  else {
    if(!GM_getValue('version_check_enabled', true))
      return;
    period = GM_getValue("version_check_delay", -1); //delay between checks (in seconds)
    if(period == -1) {
      period = 24 * 3600;
      GM_setValue("version_check_delay", period);
    }
    last = parseInt(GM_getValue("version_check_last", "0"));
    
    check = (last + period*1000) < now;
    //GM_log('previous check was at ' + ((now - last)/3600000) + ' hours ago; check = ' + check);
  }
  

  //GM_log('check ' + last + ' + ' + period + ' * 1000 - ' + now + ' = ' + (last + period*1000 - now));
  if(check) {
    GM_log('checking version update');
    GM_setValue('version_check_last', now.toString());

    loadPage($consts.version_check_url, action);
  }

}

function change_yesno(link, e) { 
  e.preventDefault(); 
  variable=link.getAttribute('variable'); 
  config_name=link.getAttribute('config_name'); 

  if(link.innerHTML == "ON" || link.innerHTML=='TAK')
    oldval = 1;
  else
    oldval = 0;

  //GM_log('change: was ' + oldval);

  val = !oldval;

  //GM_log('change: new ' + val);


  //GM_log('change: onchange new ' + val);

  if(val == oldval)
    return;

  link.innerHTML = val?"TAK":"NIE";

  if(variable != null)
    eval(variable + ' = ' + val + ';');
  if(config_name)
    GM_setValue(config_name, val);

  //GM_log('change: variable ' + variable + ' config_name ' + config_name);
  if(config_name)
    ;//GM_log(config_name + 'is ' + GM_getValue(config_name, 'unknown'));
  return val;

} 

function event_change_yesno(e) {
  change_yesno(this, e);
  return false;
}



function change_filter(num, on) {

  cname = (num!=2) ? 'cq_chi' : 'cq_cre';

  if(on==true)
    ck = cname + '=' + '1' + '; path=/' + '; domain=.salon24.pl';
  else {
    ck = cname + '=' + '1; path=/' + '; domain=.salon24.pl' + '; max-age=0' + '; expires=' + d.toGMTString();//Thu, 01-Jan-70 00:00:01 GMT;';
  }

  document.cookie = ck;

  //hack to allow open filter 2 for anybody logged or not
  if(num==2) unsafeWindow.CQ._u_acc_re = on;
  
  return on==true;
}

function get_cookies_array() {
  var cookies = document.cookie.split(' ');

  for(c=0;c<cookies.length;c++) {
    arr[c] = cookies[c].replace(/;$/,'').split('=');
  }
  return arr;
}

function get_filter(num) {
  var cookies = document.cookie.split(' ');

  cname = (num!=2) ? 'cq_chi' : 'cq_cre';

  for(c=0;c<cookies.length;c++) {
    cookies[c] = cookies[c].replace(/;$/,'');
  }

  for(c=0;c<cookies.length;c++) {
    cookie = cookies[c].split('=');
    if(cookie[0] == cname)
      return cookie[1]=='1';
  }
}

function ev_update_menu(e) { 
  change_yesno(this, e);
  apply_menu_look();
  return true;
}

function ev_change_filter1(e) { 
  on = change_yesno(this, e);
  change_filter(1, on); 
  return true;
}

function ev_change_filter2(e) { 
  on = change_yesno(this, e);
  change_filter(2, on); 
  return true;
}

/* Functions adds one On/Off setting to the menu and attaches handlers when the stat changes
 * 
 * variable - variable name (passed as string) connected to the setting
 * config_name - persistent (GM) setting name connected to the setting
 * onchange - callback function called with an event handler when state was changed
 *            should call change_yesno(this, event) first and use return value as the actual value
 * one of three above should be set, remaining can be null (but all not-null will be processed)
 * defaultval - default value used if neither 'variable' nor 'config_name' returned any
 */
function menu_yesno_add(menu, mtitle, variable, config_name, onchange, defaultval) {

  tr= document.createElement('tr');
  title = document.createElement('td');
  value  = document.createElement('td');
  avalue = document.createElement('a');
  avalue.style.cursor = 'pointer';

  title.innerHTML = mtitle;

  if(variable!=null) 
    val = eval(variable);
  else if(config_name)
    val = GM_getValue(config_name, defaultval);
  else 
    val = defaultval;

  avalue.innerHTML = (val==1) ? 'TAK' : 'NIE';

  if(variable!=null)    avalue.setAttribute('variable', variable);
  if(config_name!=null) avalue.setAttribute('config_name', config_name);

  if(onchange!=null)
    addEvent(avalue, 'click', onchange);
  else
    addEvent(avalue, 'click', event_change_yesno);


  title.style.width='250px';
  value.style.width='70px';
  tr.appendChild(title);
  value.appendChild(avalue);
  tr.appendChild(value);

  menu.appendChild(tr);

}

function menu_ro_add(menu, mtitle, mvalue) {

  tr= document.createElement('tr');
  title = document.createElement('td');
  value  = document.createElement('td');

  title.innerHTML = mtitle;
  value.innerHTML = mvalue;
  value.style.color = '#666';

  title.style.width='250px';
  value.style.width='70px';
  tr.appendChild(title);
  tr.appendChild(value);

  menu.appendChild(tr);

}

function menu_section(menu, mtitle) {
  tr= document.createElement('tr');
  title = document.createElement('th');
  title.innerHTML = mtitle;
  title.style.width='1000%';
  title.style.backgroundColor = '#ddd';
  title.style.border = '0px';
  title.style.borderBottom = '1px solid black';
  title.colSpan=2;
  tr.appendChild(title);
  menu.appendChild(tr);
}


function options_add_menu(where, showadvanced) {
  var adv = showadvanced || GM_getValue('menu_advanced', false);
  menu = document.createElement('div');
  menu.style.width='320px';
  menu.style.backgroundColor = '#eee';

  table = document.createElement('table');
  table.style.width='100%';

  menu_section(table, 'Filtry');
  menu_yesno_add(table, 'Odblokuj filtr 1', null, null, ev_change_filter1, get_filter(1));
  if(adv || $state.is_logged) menu_yesno_add(table, 'Odblokuj filtr 2', null, null, ev_change_filter2, get_filter(2));
  if(adv) menu_yesno_add(table, 'Automatycznie odblokuj filtry', null, "filter_unlock", null, 0);
  menu_section(table, 'Górne menu');
  menu_yesno_add(table, 'Skróć nazwy linków', null, "titlebar_shorten", ev_update_menu, 0);
  menu_yesno_add(table, 'Ukryj link "Start"', null, "titlebar_hide_start", ev_update_menu, 0);
  menu_yesno_add(table, 'Ukryj katalog blogów i lubczasopism', null, "titlebar_hide_catalogs", ev_update_menu, 0);
  menu_section(table, 'Lubczasopisma');
  menu_yesno_add(table, 'Popraw linki do LC na Stronie Głównej', null, "sg_fix_lc", null, 1);
  if(adv) {
    menu_section(table, 'Aktualizacje');
    menu_yesno_add(table, 'Sprawdzaj aktualizacje Salon25', null, "version_check_enabled", null, 1);
    menu_ro_add(table, 'Sprawdzaj co', GM_getValue('version_check_delay', '?')/3600 + 'h');
    menu_section(table, 'Zaawansowane');
    menu_yesno_add(table, 'Pokaż zaawansowane', null, "menu_advanced", null, 0);
  }

  menu.appendChild(table);
  
  where.appendChild(menu);

}

function onload_version_check_options_update(responseDetails) {
  nver = responseDetails.responseText;

  span = document.getElementById('options-ver');
  if(!span) return;

  text = document.createTextNode('Najnowsza dostępna wersja to ' + nver + ' ');
  span.replaceChild(text, span.firstChild);
  if(versionToInt(nver) > versionToInt($version)) {
    a = createLink('http://salon25.googlecode.com/svn/tags/v' + nver + '/salon25.user.js', '[ZAINSTALUJ]');
    a.style.color = 'blue';
    span.style.color = 'red';
    span.appendChild(a);
  }
  else
    span.style.color = 'green';
}


function options_add_footer(where) {
  div = document.createElement('div');
  div.style.color = 'gray';
  div.style.marginTop = '3em';
  div.appendChild(document.createTextNode('strona projektu: '));
  div.appendChild(createLink($consts.project_url, $consts.project_url));
  div.appendChild(document.createElement('br'));
  div.appendChild(document.createTextNode('kontakt z autorem: '));
  span = document.createElement('span');
  span.appendChild(document.createTextNode('Jan Słupski, '));
  span.style.color = 'black';
  span.appendChild(createLink('http://follow.salon24.pl/','follow.salon24.pl'));
  div.appendChild(span);
  where.appendChild(div);
}

function options_add_lead(where) {

  div = document.createElement('div');
  div.appendChild(document.createTextNode('wersja ' + $version));
  div.appendChild(document.createElement('br'));
  span = document.createElement('span');
  span.id = 'options-ver';
  a = createLink($consts.version_check_url, 'sprawdź czy dostępna jest nowsza wersja &rarr; ');
  a.style.cursor = 'pointer';
  a.style.color = 'gray';
  addEvent(a, 'click', function (e) { e.preventDefault(); this.innerHTML = 'sprawdzam'; check_updates(true, onload_version_check_options_update); } );
  span.appendChild(a);
  div.appendChild(span);

  where.appendChild(div);
  where.appendChild(document.createElement('br'));

}

function ev_show_options_page(e) {
  e.preventDefault(); 
  document.location.hash = '#salon25';

  $state.advanced_menu_magic++;

  show_options_page();
}

function show_options_page() {
  content = document.getElementById('content');
  area = getElementByClass('content-left', content, 'div');
  if(!area) area = getElementByClass('content-full', content, 'div');
  if(!area) return;

  narea = document.createElement('div');
  narea.className = 'content-left';

  h1 = document.createElement('h1');
  h1.innerHTML = 'Salon25';
  narea.appendChild(h1);

  options_add_lead(narea);
  options_add_menu(narea, $state.advanced_menu_magic>=10);
  options_add_footer(narea);
 
  content.removeChild(area);
  content.insertBefore(narea, content.firstChild);

}


function options_page() {
  if(document.location.href.slice(0,24) == "http://admin.salon24.pl/" && document.location.hash == '#salon25') {
    show_options_page();
  }

  options_page_toolbar_entry();
}


function options_page_toolbar_entry() {

  if(document.location.href.slice(0,24) != "http://admin.salon24.pl/")
    return;

  nav=document.getElementById('navigation');
  if(!nav) return;

  a = document.createElement('a');
  a.href = '/settings-account/#salon25';
  a.className = 'head';
  a.innerHTML = 'Salon25';
  li = document.createElement('li');
  list = document.createElement('ul');
  list.style.display = 'block';
  ent = document.createElement('li');
  enta = document.createElement('a');
  enta.innerHTML = 'Konfiguracja';
  enta.href = '/settings-account/#salon25';
  addEvent(enta, 'click', ev_show_options_page);
  enta.style.cursor = 'pointer';
  ent.appendChild(enta);
  list.appendChild(ent);
  li.appendChild(a);
  li.appendChild(list);
  nav.appendChild(li);
  
}

function update_discussions() {
  if(document.location.href.slice(0,22) != "http://www.salon24.pl/"
  && document.location.href.slice(0,34) != "http://www.salon24.pl/discussions/") return;

  $('.sg-left .post-list h3 a').css({'font-size':'1em'});
}

function update_main_page() {
  if(gvar.isBuggedChrome) return; //sadly

  if(document.location.href.slice(0,22) != "http://www.salon24.pl/") return;

  if(!GM_getValue('sg_fix_lc', true)) return;

  $('.post-list li').each(function() {
    var a = $(this).find('h3 a')[0];
    if(typeof(a)=='undefined') return;

    if (a.href.slice(0,32) == 'http://lubczasopismo.salon24.pl/') {
      var links = create_blog_lc_links(a);
      a.parentNode.replaceChild($elem('h3', {}, [links.direct_link]), a);

      var about = $(this).find('.author-about-body:first');
      $(about).find('span:first').remove()
      var lc_link = $(about).find('a:first').remove().get();
      lc_link.href = a.href;
      $(about).find('.cb')
              .before($elem('span', {innerHTML:'|', className:'lesep'}))
              .before($elem('span', {innerHTML:'&nbsp;Lubczasopismo: ', className: 'le'}))
              .before(lc_link);
      $(about).find('.le:first').before(links.author_link);
    }
  })
}

function create_blog_lc_links(a) {
  var link = a.href;
  var article_link = link.split("/")[link.split("/").length-1];
  var tmp = a.innerHTML.split(":");
  var nick = tmp[0];
  var rest = tmp[1];
  if(tmp.length>2) {
    for(var i=2;i<tmp.length;i++) {
      rest += ":" + tmp[i];
    }
  }
  var direct_link = $elem('a', {href : '#', innerHTML : rest});

  var author_link = $elem('a', { href : '#', 
                                 innerHTML : nick.toUpperCase(), 
                                 className : 'author-nick le',
                                 style : {color:'black'}});

  addEvent(direct_link, 'click', 
      function(e) { 
          loadPage(link, function(response) { location.href = get_author(response).blog + article_link; });
          e.preventDefault();
          return false;
      } 
  );

  addEvent(direct_link, 'mouseover', 
      function(e) { 
          loadPage(link, 
            function(response) { 
                if(direct_link.href != 'http://www.salon24.pl/#') return;
                var author = get_author(response);
                direct_link.href = author.blog + article_link;
                author_link.href = author.blog;
                author_link.style.color = "";
                author_link.className = 'author-nick le ' +author.className;
            }
          );
      } 
  );

  addEvent(author_link, 'click', 
      function(e) { 
          loadPage(link, function(response) { location.href = get_author(response).blog; });
          e.preventDefault();
          return false;
      } 
  );

  addEvent(author_link, 'mouseover', 
      function(e) { 
          loadPage(link, 
            function(response) { 
                if(author_link.href != 'http://www.salon24.pl/#') return;
                var author = get_author(response);
                author_link.href = author.blog;
                direct_link.href = author.blog + article_link;
                author_link.style.color = "";
                author_link.className = 'author-nick le ' +author.className;
            }
          );
      } 
  );

  return {'direct_link': direct_link, 'author_link':author_link}
}

function get_author(response) {
  var a = $(parseHtmlResponse(response)).find('.post-detal:first .author:first a:first')[0]
  return {'blog':a.href, 'className':a.className.split(" ")[2]}
}


function __main__() {
  GM_ApiBrowserCheck();
  init_globals();

  var err = 0;
  debug_time('START');
  check_updates(false, onload_version_check_notify);
  err = process_url();
  if(err) return err;
  err = get_my_info();
  if(err) return err;
  get_account_info();

  options_page();

  update_filters()
  update_menu();
  update_comments();
  update_post();
  update_post_edit();
  update_watched_page();
  update_tag_page();
  update_footer();
  update_main_page();
  update_discussions();

  debug_time('END');
  //update_iframe();
}

GM_ApiBrowserCheck();
if(gvar.isBuggedChrome && typeof(window.__main__) == 'undefined') {
  GM_log('applying super hack');
  super_hack();
} else {
  __main__();
}
